#include "SoundPotMainGui.h"

//==============================================================================
// quick-and-dirty function to format a timecode string
static const String timeToTimecodeString (const double seconds)
{
    const double absSecs = fabs (seconds);
    const tchar* const sign = (seconds < 0) ? T("-") : T("");

    const int hours = (int) (absSecs / (60.0 * 60.0));
    const int mins  = ((int) (absSecs / 60.0)) % 60;
    const int secs  = ((int) absSecs) % 60;

    return String::formatted (T("%s%02d:%02d:%02d:%03d"),
                              sign, hours, mins, secs,
                              roundDoubleToInt (absSecs * 1000) % 1000);
}

// quick-and-dirty function to format a bars/beats string
static const String ppqToBarsBeatsString (const double ppq,
                                          const double lastBarPPQ,
                                          const int numerator,
                                          const int denominator)
{
    if (numerator == 0 || denominator == 0)
        return T("1|1|0");

    const int ppqPerBar = (numerator * 4 / denominator);
    const double beats  = (fmod (ppq, ppqPerBar) / ppqPerBar) * numerator;

    const int bar       = ((int) ppq) / ppqPerBar + 1;
    const int beat      = ((int) beats) + 1;
    const int ticks     = ((int) (fmod (beats, 1.0) * 960.0));

    String s;
    s << bar << T('|') << beat << T('|') << ticks;
    return s;
}

#ifdef JUCE_WIN32
static HWND findMDIParentOf (HWND w)
{
    const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME);

    while (w != 0)
    {
        HWND parent = GetParent (w);

        if (parent == 0)
            break;

        TCHAR windowType [32];
        zeromem (windowType, sizeof (windowType));
        GetClassName (parent, windowType, 31);

        if (String (windowType).equalsIgnoreCase (T("MDIClient")))
        {
            w = parent;
            break;
        }

        RECT windowPos;
        GetWindowRect (w, &windowPos);

        RECT parentPos;
        GetWindowRect (parent, &parentPos);
        
        int dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left);
        int dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top);

        if (dw > 100 || dh > 100)
            break;

        w = parent;

        if (dw == 2 * frameThickness)
            break;
    }

    return w;
}
#endif


//==============================================================================
SoundPot::MainGui::MainGui (MainAudioEffect* const ownerFilter_)
    : ownerFilter (ownerFilter_)
{

	setOpaque (true);	// EditorCompWrapper

    // the filter must be valid..
    jassert (ownerFilter != 0);


	static ShinyLookAndFeel* shinyLook = 0;

    if (shinyLook == 0)
        shinyLook = new ShinyLookAndFeel();



    LookAndFeel::setDefaultLookAndFeel (shinyLook);


    // create our gain slider..
    addAndMakeVisible (gainSlider = new Slider (T("gain")));
    gainSlider->addListener (this);
    gainSlider->setRange (0.0, 1.0, 0.01);
    gainSlider->setTooltip (T("changes the volume of the audio that runs through the plugin.."));

    // get the gain parameter from the filter and use it to set up our slider
    gainSlider->setValue (1.0, false);

    // create and add the midi keyboard component..
    addAndMakeVisible (midiKeyboard 
        = new MidiKeyboardComponent (keyboardState, 
                                     MidiKeyboardComponent::horizontalKeyboard));



    // add a label that will display the current timecode and status..
    addAndMakeVisible (infoLabel = new Label (String::empty, String::empty));

    // add the triangular resizer component for the bottom-right of the UI
    addAndMakeVisible (resizer = new ResizableCornerComponent (this, &resizeLimits));
    resizeLimits.setSizeLimits (150, 150, 800, 300);

    // set our component's initial size to be the last one that was stored in the filter's settings
    setSize (ownerFilter->lastUIWidth, 
             ownerFilter->lastUIHeight);

	// EditorCompWrapper
#ifdef JUCE_WIN32
	addMouseListener (this, true);
#endif
			 

    // register ourselves with the filter - it will use its ChangeBroadcaster base 
    // class to tell us when something has changed, and this will call our changeListenerCallback()
    // method.

    ownerFilter->addChangeListener (this);
}

SoundPot::MainGui::~MainGui()
{
    ownerFilter->removeChangeListener (this);

    deleteAllChildren();

    // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
    // filter for some reason..
    // jassert (ownerFilter->activeEditor != this);
}



void SoundPot::MainGui::paintOverChildren (Graphics& g) // EditorCompWrapper
{
	// this causes an async call to masterIdle() to help
	// creaky old DAWs like Nuendo repaint themselves while we're
	// repainting. Otherwise they just seem to give up and sit there
	// waiting.
	triggerAsyncUpdate();
}

void SoundPot::MainGui::handleAsyncUpdate()	// EditorCompWrapper
{
    ownerFilter->tryMasterIdle();
}


void SoundPot::MainGui::moved() // EditorCompWrapper
{
	boundsChanged(); // adapt host window to current size
}

void SoundPot::MainGui::boundsChanged () // EditorCompWrapper
{

    const int cw = getWidth();
    const int ch = getHeight();

    ownerFilter->resizeHostWindow (cw, ch);

#ifdef JUCE_MAC
    ownerFilter->resizeHostWindow (cw, ch);  // (doing this a second time seems to be necessary in tracktion)
#endif
}




void SoundPot::MainGui::mouseDown (const MouseEvent&)	// EditorCompWrapper
{
	broughtToFront();
}

void SoundPot::MainGui::broughtToFront()	// EditorCompWrapper
{
	// for hosts like nuendo, need to also pop the MDI container to the
	// front when our comp is clicked on.
	HWND parent = findMDIParentOf ((HWND) getWindowHandle());

	if (parent != 0)
	{
		SetWindowPos (parent, 
					  HWND_TOP, 
					  0, 0, 0, 0,
					  SWP_NOMOVE | SWP_NOSIZE);
	}
}





void SoundPot::MainGui::paint (Graphics& g)
{
    // just clear the window
    g.fillAll (Colour::greyLevel (0.9f));
}

void SoundPot::MainGui::resized()
{
	boundsChanged(); // EditorCompWrapper (adapt host window to current size)
    gainSlider->setBounds (10, 10, 200, 22);
    infoLabel->setBounds (10, 35, 450, 20);

    const int keyboardHeight = 70;
    midiKeyboard->setBounds (4, getHeight() - keyboardHeight - 4, 
                             getWidth() - 8, keyboardHeight);

    resizer->setBounds (getWidth() - 16, getHeight() - 16, 16, 16);

    // if we've been resized, tell the filter so that it can store the new size
    // in its settings
	


    ownerFilter->lastUIWidth = getWidth();
    ownerFilter->lastUIHeight = getHeight();

}

//==============================================================================
void SoundPot::MainGui::changeListenerCallback (void* source)
{
    // this is the filter telling us that it's changed, so we'll update our
    // display of the time, midi message, etc.
    updateParametersFromFilter();
}

void SoundPot::MainGui::sliderValueChanged (Slider*)
{
	ownerFilter->setParameterAutomated(0, (float) gainSlider->getValue());
}

//==============================================================================
void SoundPot::MainGui::updateParametersFromFilter()
{

    // we use this lock to make sure the processBlock() method isn't writing to the
    // lastMidiMessage variable while we're trying to read it, but be extra-careful to
    // only hold the lock for a minimum amount of time..
    ownerFilter->getCallbackLock().enter();

    // take a local copy of the info we need while we've got the lock..
	const SoundPot::CurrentPositionInfo positionInfo (ownerFilter->lastPosInfo);
    const float newGain = ownerFilter->getParameter (0);

    // ..release the lock ASAP
    ownerFilter->getCallbackLock().exit();


    // ..and after releasing the lock, we're free to do the time-consuming UI stuff..
    String infoText;

    infoText << String (positionInfo.bpm, 2) << T(" bpm, ")
             << positionInfo.timeSigNumerator << T("/") << positionInfo.timeSigDenominator
             << T("  -  ") << timeToTimecodeString (positionInfo.timeInSeconds) 
             << T("  -  ") << ppqToBarsBeatsString (positionInfo.ppqPosition,
                                                    positionInfo.ppqPositionOfLastBarStart,
                                                    positionInfo.timeSigNumerator,
                                                    positionInfo.timeSigDenominator);
	
    if (positionInfo.isPlaying)
        infoText << T("  (playing)");

    infoLabel->setText (infoText, false);

    /* Update our slider.
    
       (note that it's important here to tell the slider not to send a change 
       message, because that would cause it to call the filter with a parameter 
       change message again, and the values would drift out.
    */

	gainSlider->setValue (newGain, false);


	// Restore size
    setSize (ownerFilter->lastUIWidth, 
             ownerFilter->lastUIHeight);

}



